// pages/orderList/orderList.js
Page({
  data: {
    currentTab: 0,
    refreshing: false,
    
    // 各状态订单数量
    pendingPayCount: 0,
    pendingServiceCount: 0,
    inServiceCount: 0,
    
    // 订单列表数据
    pendingPayOrders: [],
    pendingServiceOrders: [],
    inServiceOrders: [],
    completedOrders: [],

    // 底部导航图标
    navIcons: {
      home: '',
      category: '',
      order: '',
      profile: ''
    }
  },

  onLoad: function (options) {
    // 如果有传入的tab参数，切换到对应标签
    if (options.tab) {
      this.setData({
        currentTab: parseInt(options.tab)
      });
    }
    
    this.loadOrderData();
  },

  onShow: function () {
    this.loadOrderData();
  },

  // 切换标签
  switchTab: function (e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentTab: index
    });
    
    // 加载对应标签的数据
    this.loadOrderData();
  },

  // 下拉刷新
  onRefresh: function () {
    this.setData({
      refreshing: true
    });
    
    this.loadOrderData().finally(() => {
      this.setData({
        refreshing: false
      });
    });
  },

  // 加载订单数据
  loadOrderData: function () {
    return new Promise((resolve, reject) => {
      // 模拟API调用
      wx.showLoading({
        title: '加载中...'
      });

      // 模拟数据
      setTimeout(() => {
        const mockData = this.getMockOrderData();
        
        this.setData({
          pendingPayOrders: mockData.pendingPay,
          pendingServiceOrders: mockData.pendingService,
          inServiceOrders: mockData.inService,
          completedOrders: mockData.completed,
          pendingPayCount: mockData.pendingPay.length,
          pendingServiceCount: mockData.pendingService.length,
          inServiceCount: mockData.inService.length
        });

        // 启动倒计时
        this.startCountdown();
        
        wx.hideLoading();
        resolve();
      }, 1000);
    });
  },

  // 获取模拟数据
  getMockOrderData: function () {
    return {
      pendingPay: [
        {
          id: '1',
          orderNo: 'GP202309301001',
          gameName: '猛攻单',
          playDuration: 2,
          playType: '顶级挑战',
          gameRank: '星耀III',
          price: '50.00',
          gameAvatar: '/images/game1.jpg',
          countdown: '14:32',
          countdownSeconds: 872
        }
      ],
      pendingService: [
        {
          id: '2',
          orderNo: 'GP202309301002',
          gameName: '英雄联盟',
          playDuration: 3,
          playType: '娱乐陪玩',
          gameRank: '黄金I',
          price: '45.00',
          gameAvatar: '/images/game2.jpg',
          companionName: '小雨陪玩',
          appointmentTime: '今天 20:00-23:00'
        }
      ],
      inService: [
        {
          id: '3',
          orderNo: 'GP202309301003',
          gameName: '和平精英',
          playDuration: 4,
          playType: '技术陪玩',
          gameRank: '不朽星钻',
          price: '60.00',
          gameAvatar: '/images/game3.jpg',
          companionName: '大神带飞',
          progress: 65,
          playedTime: 2.6,
          currentStatus: '正在游戏中...'
        }
      ],
      completed: [
        {
          id: '4',
          orderNo: 'GP202309291001',
          gameName: '原神',
          playDuration: 2,
          playType: '剧情陪玩',
          gameRank: '冒险等级55',
          price: '40.00',
          gameAvatar: '/images/game4.jpg',
          companionName: '温柔小姐姐',
          completeTime: '2023-09-29 22:30',
          rating: 5,
          ratingText: '陪玩很有耐心，游戏技术也很好',
          gameRecord: {
            wins: 8,
            losses: 2,
            mvp: 3
          }
        }
      ]
    };
  },

  // 启动倒计时
  startCountdown: function () {
    const that = this;
    
    setInterval(() => {
      const pendingPayOrders = that.data.pendingPayOrders.map(order => {
        if (order.countdownSeconds > 0) {
          order.countdownSeconds--;
          const minutes = Math.floor(order.countdownSeconds / 60);
          const seconds = order.countdownSeconds % 60;
          order.countdown = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        } else {
          order.countdown = '00:00';
        }
        return order;
      });
      
      that.setData({
        pendingPayOrders
      });
    }, 1000);
  },

  // 取消订单
  cancelOrder: function (e) {
    const orderId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '确认取消',
      content: '确定要取消这个订单吗？',
      success: (res) => {
        if (res.confirm) {
          this.handleCancelOrder(orderId);
        }
      }
    });
  },

  handleCancelOrder: function (orderId) {
    wx.showLoading({
      title: '处理中...'
    });
    
    // 模拟API调用
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '订单已取消',
        icon: 'success'
      });
      
      this.loadOrderData();
    }, 1500);
  },

  // 立即支付
  payOrder: function (e) {
    const orderId = e.currentTarget.dataset.id;
    
    wx.showLoading({
      title: '跳转支付...'
    });
    
    // 模拟跳转支付
    setTimeout(() => {
      wx.hideLoading();
      wx.navigateTo({
        url: `/pages/payment/payment?orderId=${orderId}`
      });
    }, 1000);
  },

  // 申请退款
  requestRefund: function (e) {
    const orderId = e.currentTarget.dataset.id;
    
    wx.navigateTo({
      url: `/pages/refund/refund?orderId=${orderId}`
    });
  },

  // 联系客服
  contactService: function (e) {
    wx.makePhoneCall({
      phoneNumber: '400-123-4567'
    });
  },

  // 联系陪玩师
  contactCompanion: function (e) {
    const orderId = e.currentTarget.dataset.id;
    
    wx.navigateTo({
      url: `/pages/chat/chat?orderId=${orderId}`
    });
  },

  // 查看游戏详情
  trackService: function (e) {
    const orderId = e.currentTarget.dataset.id;
    
    wx.navigateTo({
      url: `/pages/gameDetail/gameDetail?orderId=${orderId}`
    });
  },

  // 查看订单详情
  viewOrderDetail: function (e) {
    const orderId = e.currentTarget.dataset.id;
    
    wx.navigateTo({
      url: `/pages/orderDetail/orderDetail?orderId=${orderId}`
    });
  },

  // 评价陪玩
  rateOrder: function (e) {
    const orderId = e.currentTarget.dataset.id;
    
    wx.navigateTo({
      url: `/pages/rating/rating?orderId=${orderId}`
    });
  },

  // 再次预约
  reorder: function (e) {
    const orderId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '再次预约',
      content: '是否使用相同的陪玩配置重新预约？',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: `/pages/booking/booking?reorderId=${orderId}`
          });
        }
      }
    });
  },

  // 底部导航点击
  onNavTap: function(e) {
    const navType = e.currentTarget.dataset.type;
    switch (navType) {
      case 'home':
        wx.reLaunch({
          url: '/pages/index/index',
        })
        break;
      case 'category':
        wx.reLaunch({
          url: '/pages/classify/classify',
        })
        break;
      case 'order':
        // 当前页面，不需要跳转
        break;
      case 'profile':
        wx.reLaunch({
          url: '/pages/user/user',
        })
        break;
    }
  }
});